/**
 * 
 */
package com.easidea.tim.service.inventory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springside.core.service.EntityService;

import com.easidea.tim.dao.inventory.StorageDao;
import com.easidea.tim.entity.inventory.Storage;
import com.easidea.tim.util.Page;

/**
 * @author Harrison
 * 
 */
public class StorageService extends EntityService<Storage, StorageDao> {
	private static Logger log = Logger.getLogger(StorageService.class);
	private StorageDao storageDao;

	/**
	 * 根据布品ID、色号、是否剪样、米数检查当前库存数量是否足够
	 * 
	 * @param productId
	 * @param colorCode
	 * @param isSample
	 * @param meterNum
	 * @return
	 */
	public boolean canTakeSalesOrder(Long productId, String colorCode,
			Boolean isSample, Float meterNum) {
		if (productId == null || colorCode == null || meterNum == null) {
			log
					.error("parameters can not be null with productId / colorCode / meterNum in canTakeSalesOrder method ... ");
			return false;
		}
		Criteria cte = createUnDeletedCriteria();
		cte.createAlias("product", "product");
		cte.add(Restrictions.eq("product.id", productId));
		cte.add(Restrictions.eq("product.colorCode", colorCode));
		cte.add(Restrictions.eq("product.dummyFlag", false)); //挂板支持
		if (isSample != null)
			cte.add(Restrictions.eq("sampleFlag", isSample));
		cte.setProjection(Projections.sum("meterNum"));
		cte.setFetchSize(1);
		Float totalQuantity = ((BigDecimal) cte.uniqueResult()).floatValue();
		if (totalQuantity != null && totalQuantity > meterNum) {
			log
					.debug("current storage meter quantity is biger than required , productId: "
							+ productId
							+ " colorCode: "
							+ colorCode
							+ " isSample: "
							+ isSample
							+ " Required: "
							+ meterNum);
			return true;
		} else {
			log
					.debug("Oops, current storage meter quantity need filled in, productId: "
							+ productId
							+ " colorCode: "
							+ colorCode
							+ " isSample: "
							+ isSample
							+ " Required: "
							+ meterNum);
		}
		return false;
	}

	/**
	 * 根据布品名称、色号、是否剪样、米数检查当前库存数量是否足够
	 * 
	 * @param productName
	 * @param colorCode
	 * @param isSample
	 * @param meterNum
	 * @return
	 */
	public boolean canTakeSalesOrder(String productName, String colorCode,
			Boolean isSample, Float meterNum) {
		if (productName != null && productName.trim().length() > 0
				&& colorCode != null && meterNum != null) {
			Criteria cte = createUnDeletedCriteria();
			cte.createAlias("product", "product");
			cte.add(Restrictions.eq("product.name", productName));
			cte.add(Restrictions.eq("product.colorCode", colorCode));
			cte.add(Restrictions.eq("product.dummyFlag", false)); //挂板支持
			if (isSample != null)
				cte.add(Restrictions.eq("sampleFlag", isSample));
			cte.setProjection(Projections.sum("meterNum"));
			cte.setFetchSize(1);
			Float totalQuantity = ((BigDecimal) cte.uniqueResult()).floatValue();

			if (totalQuantity != null && totalQuantity > meterNum) {
				log
						.debug("current storage meter quantity is biger than required , productName: "
								+ productName
								+ " colorCode: "
								+ colorCode
								+ " isSample: "
								+ isSample
								+ " Required: "
								+ meterNum);
				return true;
			} else {
				log
						.debug("Oops, current storage meter quantity need filled in, productName: "
								+ productName
								+ " colorCode: "
								+ colorCode
								+ " isSample: "
								+ isSample
								+ " Required: "
								+ meterNum);
			}
		} else {
			log
					.error("parameters can not be null with productName / colorCode / meterNum in canTakeSalesOrder method ... ");
		}
		return false;
	}


	/**
	 * 填充
	 * @param productName
	 * @param productColor
	 * @param soflowNo
	 * @param meter
	 * @return
	 */
	public String isCompleteProduct(String productName, String productColor,
			String soflowNo, String meter) {
		storageDao.cancelChargedStorage(productName, productColor, soflowNo);
		String result = "";
		String tmp = "";
		String meters[] = meter.split(",");
		Double meterf[] = new Double[meters.length];
		for (int i = 0; i < meters.length; i++) {
			meterf[i] = Double.valueOf(meters[i]);
		}
		Set<Short> chargeset = storageDao.inChargeStorage(productName, productColor,
				soflowNo, meterf);
		Iterator<Short> ir = chargeset.iterator();
		while (ir.hasNext()) {
			tmp = new Short(ir.next()).toString();
			if (tmp.equals("-1")) {
				result = "-1";
				break;
			} else {
				result = result + tmp + ",";
			}
		}
		return result;
	}

	/**
	 * 库存列表查询
	 * 
	 * @param productName
	 * @param colorCode
	 * @param isSample
	 * @param page
	 * @return
	 */
	public Page listProductStorage(String productName, String colorCode,
			Boolean isSample, Page page, Boolean isIncludeChargedStorage) {
		
		Map<String, Object> rtnMap = storageDao
				.pagedQueryStorageList(productName, colorCode, isSample, page,
						isIncludeChargedStorage);
		
		Integer totalCounts = (Integer) rtnMap.get("totalCounts");
		Integer startIndex = (Integer) rtnMap.get("startIndex");
		List<Object[]> dataList = (List<Object[]>) rtnMap.get("data");
		Page rtnPage = (page == null) ? new Page(0,0,0,dataList) : new Page(startIndex, totalCounts, page.getPageSize(),
				dataList);
		return rtnPage;
	}

	/**
	 * 根据单品名称，查询总匹数和米数
	 * 
	 * @param productName
	 * @return
	 */
	public Map<String, Double> searchProductTotally(String productName,
			Boolean isSample, Boolean isIncludeCharged) {
		Map<String, Double> rtnMap = null;
		if (productName != null && StringUtils.isNotEmpty(productName)) {
			rtnMap = new HashMap<String, Double>();
			Criteria cte = storageDao.createUnDeletedCriteria();
			cte.createAlias("product", "product");
			cte.add(Restrictions.eq("product.name", productName));
			cte.add(Restrictions.eq("product.dummyFlag", false)); //挂板支持
			if (isSample != null)
				cte.add(Restrictions.eq("sampleFlag", isSample));
			if (isIncludeCharged != null && !isIncludeCharged)
				cte.add(Restrictions.eq("chargeFlag", isIncludeCharged));
			cte.setProjection(Projections.count("id"));
			Integer totalPiNum = (Integer) cte.uniqueResult();
			rtnMap.put("totalPiNum", totalPiNum.doubleValue());

			Criteria cte2 = storageDao.createUnDeletedCriteria();
			cte2.createAlias("product", "product");
			cte2.add(Restrictions.eq("product.name", productName));
			cte2.add(Restrictions.eq("product.dummyFlag", false)); //挂板支持
			if (isSample != null)
				cte2.add(Restrictions.eq("sampleFlag", isSample));
			if (isIncludeCharged != null && !isIncludeCharged)
				cte2.add(Restrictions.eq("chargeFlag", isIncludeCharged));
			cte2.setProjection(Projections.sum("meterNum"));
			Double totalMeterNum = (Double)cte2.uniqueResult();
			rtnMap.put("totalMeterNum", totalMeterNum);
		}
		return rtnMap;
	}

	/**
	 * 根据品名、色号、剪样标识，提取清单明细数据
	 * 
	 * @param productName
	 * @param colorCode
	 * @param isSample
	 * @return
	 */
	public List<Storage> listStorageDetail(String productName,
			String colorCode, Boolean isSample, Boolean chargeFlag) {
		Criteria cte = createUnDeletedCriteria();
		cte.createAlias("product", "product");
		cte.add(Restrictions.eq("product.name", productName));
		cte.add(Restrictions.eq("product.colorCode", colorCode));
		cte.add(Restrictions.eq("product.dummyFlag", false)); //挂板支持
		cte.add(Restrictions.eq("sampleFlag", isSample));
		if(!chargeFlag)cte.add(Restrictions.eq("chargeFlag", chargeFlag));
		List<Storage> lst = (List<Storage>) cte.list();
		return lst;
	}

	/**
	 * 根据销售订单编号，提取已经填充的库存数据
	 * 
	 * @param saleOrderId
	 * @return
	 */
	public List<Storage> listStorageBySaleOrder(Long saleOrderId) {
		return storageDao.getStorageBySaleOrderId(saleOrderId);
	}
	
	/**
	 * 获得总库存信息
	 * @return
	 */
	public Map<String, Double> getStorageSummary(){
		return storageDao.getStorageSummary();
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.easidea.tim.dao.inventory.StorageDao#validateSampleStorageLimitaion(String,String)
	 */
	public boolean validateSampleStorageLimitaion(String name, String colorCode){
		return storageDao.validateSampleStorageLimitaion(name, colorCode);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springside.core.service.EntityService#getEntityDao()
	 */
	@Override
	public StorageDao getEntityDao() {
		return storageDao;
	}

	/**
	 * @return the storageDao
	 */
	public StorageDao getStorageDao() {
		return storageDao;
	}

	/**
	 * @param storageDao
	 *            the storageDao to set
	 */
	public void setStorageDao(StorageDao storageDao) {
		this.storageDao = storageDao;
	}
}
